/**
 * @author luguoxiang
 * @date 2021-09-07
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
import { getRefreshToken, request, signout, syncLockLoad, toMd5 } from '@/soar';

const baseUrl = '/system/account';

type QueryEnum = 'user' | 'role' | 'menu' | 'permit';

/**
 * 退出登录
 */
export function logout(): Promise<any> {
  return request
    .post(`${baseUrl}/logout`, {
      errorMsg: false,
    })
    .finally(() => {
      signout();
    });
}

/**
 * 获取用户信息
 * @param queryEnums 要返回的数据（默认全部）
 * @param systems 过滤菜单系统（默认全部）
 */
export function getUserInfo(queryEnums?: QueryEnum[], systems?: string[]): Promise<any> {
  return syncLockLoad(`${baseUrl}/info`, (url: string) => {
    return request.get(url, { params: { queryEnums, systems }, timeout: 10000 });
  });
}

/**
 * 修改密码
 * @returns {Promise<any>}
 */
export function updatePassword(body: { oldPassword: string; newPassword: string }): Promise<any> {
  return request.post(`${baseUrl}/update-password`, {
    data: {
      oldPassword: toMd5(body.oldPassword.trim()),
      newPassword: toMd5(body.newPassword.trim()),
    },
    title: '修改密码',
  });
}

/**
 * 修改账号信息
 * @returns {Promise<any>}
 */
export function updateInfo(data: { nickname?: string; avatar?: string }): Promise<any> {
  return request.post(`${baseUrl}/update-info`, {
    data,
    title: '修改账号信息',
  });
}

/**
 * 菜单
 * @returns {Promise<any>}
 */
export function menus(): Promise<any> {
  return request.get(`${baseUrl}/menus`, {
    title: '菜单',
  });
}

/**
 * 角色
 * @returns {Promise<any>}
 */
export function roles(): Promise<any> {
  return request.get(`${baseUrl}/roles`, {
    title: '角色',
  });
}

/**
 * 组织机构
 * @returns {Promise<any>}
 */
export function orgs(): Promise<any> {
  return request.get(`${baseUrl}/orgs`, {
    title: '组织机构',
  });
}

/**
 * 岗位
 * @returns {Promise<any>}
 */
export function posts(): Promise<any> {
  return request.get(`${baseUrl}/posts`, {
    title: '岗位',
  });
}

/**
 * 绑定的账号
 * @returns {Promise<any>}
 */
export function accounts(): Promise<any> {
  return request.get(`${baseUrl}/accounts`, {
    title: '绑定的账号',
  });
}

/**
 * 租户列表
 * @returns {Promise<any>}
 */
export function tenants(): Promise<any> {
  return request.get(`${baseUrl}/tenants`, {
    title: '租户列表',
  });
}

/**
 * 切换租户
 * @param tenantId
 */
export function changeTenant(tenantId: string) {
  return request.post(`${baseUrl}/change-tenant`, {
    title: '切换租户',
    data: {
      tenantId,
      refreshToken: getRefreshToken(),
    },
  });
}

/**
 * 解绑账号
 */
export function unbindAccount(data: { accountType: number; account: string }) {
  return request.post(`${baseUrl}/unbind-account`, {
    title: '解绑账号',
    data,
  });
}
